package com.hujing;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch使用
 * CountDownLatch是一个同步工具类，它允许一个或多个线程等待其他线程完成一系列操作之后再运行
 */
public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {
        int threadCount = 3;
        CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        for (int i = 0; i < threadCount; i++) {
            int finalI = i + 1;
            new Thread(() -> {
                try {
                    System.out.println("线程" + finalI + "开始执行");
                    Thread.sleep(2000);
                    System.out.println("线程" + finalI + "执行完毕");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    countDownLatch.countDown();
                }
            }).start();
        }

        countDownLatch.await();
        System.out.println("所有线程执行完毕");
    }
}
